package com.cweb.admin.serivce.wxMp;


import com.cweb.framework.base.serivce.BaseSerivce;
import com.cweb.framework.pojo.CustomException;
import com.cweb.framework.util.ErrorEnum;
import com.cweb.admin.model.wx.wx_platform_info.entity.WxPlatformInfo;
import com.cweb.admin.model.wx.wx_platform_info.service.WxPlatformInfoService;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 微信公众号相关服务
 */
@Service
public class WeixinMpSerivce extends BaseSerivce {
    // 存放不同的微信服务
    private final Map<Long, WxMpService> mapMpService = new ConcurrentHashMap<>();

    @Autowired
    private WxPlatformInfoService wxPlatformInfoService;

    /**
     * 初始化
     */
    public WxMpService init(Long platformId) throws CustomException {
        log.info("微信公众号相关服务 -- 初始化 --");
        if (mapMpService.containsKey(platformId)){
            return mapMpService.get(platformId);
        }
        // 查询处理
        WxPlatformInfo wxPlatformInfo = wxPlatformInfoService.getById(platformId);
        if(null == wxPlatformInfo){
            throw new CustomException(ErrorEnum.API_PLATFORM_NO_ID);
        }
        // 初始化配置
        WxMpDefaultConfigImpl config = new WxMpDefaultConfigImpl();
        config.setAppId(wxPlatformInfo.getKey());
        config.setSecret(wxPlatformInfo.getSecret());
        config.setToken(wxPlatformInfo.getToken());
        config.setAesKey(wxPlatformInfo.getEncodingAesKey());
        // 服务实例对象
        WxMpService mpService = new WxMpServiceImpl();
        mpService.setWxMpConfigStorage(config);
        mapMpService.put(platformId, mpService);
        return mpService;
    }

    /**
     * 取得服务
     */
    public WxMpService getService(Long platformId) throws CustomException {
        if (mapMpService.containsKey(platformId)){
            return mapMpService.get(platformId);
        }
        throw new CustomException(ErrorEnum.API_PLATFORM_NO_SERVICE);
    }

    /**
     * 取得用户信息
     */
    public WxMpUser getUserInfo(Long platformId, String openid) throws CustomException {
        WxMpService wxMpService = getService(platformId);
        try {
            return wxMpService.getUserService().userInfo(openid);
        } catch (WxErrorException e) {
            throw new CustomException(ErrorEnum.API_WEIXIN_API_USER_INFO_ERROR);
        }
    }


    /**
     * 路由返回
     */
    public WxMpMessageRouter newRouter(Long platformId) throws CustomException {
        final WxMpMessageRouter newRouter = new WxMpMessageRouter(getService(platformId));
        return newRouter;
    }
}
